package com.cluster.user.controller;

import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api")
@CrossOrigin
public class FileUploadController {

    private static final String SFTP_HOST = "61.155.146.227";
    private static final String SFTP_USER = "root";
    private static final String SFTP_PASSWORD = "k_!Rc9!UMKVs*P";

    private static final String REMOTE_SERVER_DIR = "/data/upload_file_rule/";
    private static final String REMOTE_ENV_DIR = "/data/env/";

    @PostMapping("/upload")
    @ResponseBody
    public AjaxResult uploadFile(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return AjaxResult.error("文件不能为空");
        }

        String fileName = file.getOriginalFilename();
        Session session = null;
        ChannelSftp channelSftp = null;
        String fileUrl = "";

        try {
            // 创建 SSH 会话
            JSch jsch = new JSch();
            session = jsch.getSession(SFTP_USER, SFTP_HOST, 22);
            session.setPassword(SFTP_PASSWORD);
            session.setConfig("StrictHostKeyChecking", "no");
            session.connect();

            // 打开 SFTP 通道
            channelSftp = (ChannelSftp) session.openChannel("sftp");
            channelSftp.connect();


            // 获取文件输入流并上传
            try (InputStream inputStream = file.getInputStream()) {
                channelSftp.put(inputStream, REMOTE_SERVER_DIR + fileName);
            }

            // 返回上传结果
            fileUrl = REMOTE_SERVER_DIR + fileName;


            AjaxResult ajax = AjaxResult.success("文件上传成功！");
            ajax.put("fileName", fileName);
            ajax.put("url", fileUrl);

            return ajax;
        } catch (Exception e) {
            return AjaxResult.error("文件上传失败: " + e.getMessage());
        } finally {
            // 关闭通道和会话
            if (channelSftp != null && channelSftp.isConnected()) {
                channelSftp.disconnect();
            }
            if (session != null && session.isConnected()) {
                session.disconnect();
            }
        }
    }



}
